<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i>扩展属性</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <div class="grid-content bg-purple">
                            <el-input
                                v-model="query.name"
                                placeholder="名称"
                                class="handle-input mr10"
                                @keyup.enter.native="handleSearch"
                            ></el-input>
                        </div>
                    </el-col>
                    <el-col :span="4">
                        <el-select v-model="query.categoryId" clearable filterable placeholder="-所属类别-">
                            <el-option v-for="item in selectCategory" :key="item.id" :label="item.title" :value="item.id">
                                <span :style="item.parentId == 0 ? '' : 'padding-left:10px;'">{{ item.title }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="8">
                        <div class="grid-content bg-purple">
                            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                            <el-button type="primary" icon="el-icon-plus" @click="handleEdit()">新增</el-button>
                        </div>
                    </el-col>
                </el-row>
            </div>

            <el-table
                v-loading="loading"
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                row-key="id"
            >
                <el-table-column class-name="user2" prop="name" label="名称"></el-table-column>
                <el-table-column prop="categoryId" :formatter="categoryFilter" label="所属类别" align="center"></el-table-column>

                <el-table-column class-name="user2" prop="remark" label="备注"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope" v-if="1 == 1">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    background
                    @current-change="handleCurrentChange"
                    :current-page="1"
                    :page-sizes="[10, 15, 20, 30]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal"
                >
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :close-on-click-modal="false" title="自定义属性" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="100px" :rules="rulesForm">
                <el-form-item label="属性名称" prop="name">
                    <el-input v-model="form.name" id="name"></el-input>
                </el-form-item>

                <el-form-item label="所属分类">
                    <el-select v-model="form.categoryId" clearable filterable placeholder="-所属类别-">
                        <el-option v-for="item in selectCategory" :key="item.id" :label="item.title" :value="item.id">
                            <span :style="item.parentId == 0 ? '' : 'padding-left:10px;'">{{ item.title }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="文本类型" prop="dataType">
                    <el-radio v-model="dataType" label="textbox">文本框</el-radio>
                    <el-radio v-model="dataType" label="textarea">多行文本框</el-radio>
                </el-form-item> -->
                <el-form-item label="备注信息" prop="remark">
                    <el-input id="remark" type="textarea" :rows="3" placeholder="不超过50个字" v-model="form.remark"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm('form')">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    name: 'user_list',
    data() {
        return {
            query: {
                name: '',
                categoryId: '',
                pageIndex: 1,
                pageSize: 10
            },
            dataType: 'textbox',
            tableData: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            selectCategory: [],
            editSlectCategory: [],
            loading: false,
            slectCategory: '',
            rulesForm: {
                name: [
                    {
                        required: true,
                        message: '请输入属性名称!'
                    },
                    {
                        min: 2,
                        max: 20,
                        message: '长度在 2 到 20 个字符'
                    }
                ],
                defaultValue: [
                    {
                        min: 0,
                        max: 50,
                        message: '长度不能超过50个字符'
                    }
                ]
            }
        };
    },
    created() {
        this.loading = true;
        this.getData();
        this.getCategorySelect();
    },
    methods: {
        categoryFilter(row, column) {
            var str = this.selectCategory.filter((c) => c.id == row.categoryId);
            if (str.length > 0) return str[0].title;
            else return '';
        },
        stateFilter(row, column) {
            var str = '';
            switch (String(row.dataType).toLowerCase()) {
                case 'textbox':
                    str = '文本';
                    break;
                case 'textarea':
                    str = '多行文本';
                    break;
                default:
                    str = row.dataType;
                    break;
            }
            return str;
        },

        // 触发搜索按钮
        handleSearch() {
            this.query.pageIndex = 1;
            this.getData();
        },

        getData() {
            this.loading = true;

            var cid = this.query.categoryId || '';
            var categoryIds = [];
            if (cid != '') categoryIds.push(cid);

            var parmas = {
                name: this.query.name,
                categoryId: categoryIds,
                pageIndex: this.query.pageIndex,
                pageSize: this.query.pageSize
            };
            axios({
                url: config.gatewayUrl + '/api/product/attr/paged',
                method: 'post',
                data: parmas
            }).then((res) => {
                this.tableData = res.data.items;
                this.pageTotal = res.data.totalCount;
                this.loading = false;
            });
        },
        getCategorySelect() {
            var query = {
                title: '',
                parentId: null,
                pageIndex: 1,
                pageSize: 100
            };
            axios({
                url: config.gatewayUrl + '/api/product/cat/paged',
                method: 'post',
                data: query
            }).then((res) => {
                if (res.data && res.data.items.length > 0) {
                    var firstCategory = res.data.items.filter(function (item) {
                        return item.parentId == 0;
                    });
                    var secondCategory = res.data.items.filter(function (item) {
                        return item.parentId > 0;
                    });

                    var st = [];

                    for (let index = 0; index < firstCategory.length; index++) {
                        st.push(firstCategory[index]);
                        var t = secondCategory.filter(function (item) {
                            return item.parentId == firstCategory[index].id;
                        });
                        st = st.concat(t);
                    }
                    this.selectCategory = st;
                    this.editSlectCategory = st;
                }
            });
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            var that = this;
            this.$confirm('确定要删除【' + row.name + '】吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    axios({
                        url: config.gatewayUrl + '/api/product/attr/delete?id=' + row.id,
                        method: 'get',
                        //data: parmas
                    }).then((res) => {
                        that.getData();
                        that.tableData.splice(index, 1);
                        that.$message.success('删除成功');
                    });
                })
                .catch(() => {});
        },

        // 编辑操作
        handleEdit(index, row) {
            if (row) {
                this.idx = index;
                this.form = row;

            } else {
                if (this.selectCategory.length > 0) {
                    this.form.categoryId = this.selectCategory[0].id;
                }
                this.form.dataType = 'textbox';
            }

            this.editVisible = true;
        },
        // 保存编辑
        saveEdit(formName) {
            var that = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    var dto = this.form;
                    debugger;
                    dto.dataType = this.dataType;
                    axios
                        .post(config.gatewayUrl + '/api/product/attr/create', dto)
                        .then((res) => {
                            if (res.data.result == false) {
                                that.$message.error(res.data.promptMsg);
                                console.log(res);
                            } else {
                                that.$refs.form.clearValidate();
                                //that.editVisible = false;
                                that.closeDialog();
                                that.$message.success(`保存成功!`);
                                that.getData();
                            }
                        })
                        .catch((error) => {
                            console.log(error); //  错误处理 相当于error
                        });
                    that.$refs.form.clearValidate();
                } else {
                    return false;
                }
            });
        },

        closeDialog() {
            this.selectRole = [];
            var that = this;
            this.form = {
                id: '',
                name: '',
                dataType: 'textbox',
                defaultValue: '',
                categoryId: '',
                remark: ''
            };
            setTimeout(function () {
                that.$refs.form.clearValidate();
            }, 100);
            this.editVisible = false;
        },
        resetForm(formName) {
            this.form = {
                id: '',
                name: '',
                dataType: 'textbox',
                defaultValue: '',
                categoryId: '',
                remark: ''
            };
            this.dataType = 'textbox';
            this.editVisible = false;
            var that = this;
            setTimeout(function () {
                that.$refs.form.clearValidate();
            }, 100);
        },
        // 分页导航
        handlePageChange(val) {
            //跳转到
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        handleSizeChange(val) {
            //改变页码
            this.query.pageSize = val;
            this.getData();
        },
        handleCurrentChange(val) {
            //下一页console.log(`当前页: ${val}`);
            this.query.pageIndex = val;
            this.getData();
        }
    },
    watch: {}
};
</script>